package com.lin.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.lin.utils.JdbcUtils;
import com.lin.vo.Category;
import java.sql.Connection;
public class CategoryDaoImpl implements ICategoryDao {

	@Override
	public List<Category> findAllCategory() {
       QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
       String sql="SELECT * FROM category";
       List<Category> categoryLists;
       try {
    	   categoryLists = queryRunner.query(sql, new BeanListHandler<>(Category.class));
	} catch (SQLException e) {
		e.printStackTrace();
		throw new RuntimeException();
	}
	   return categoryLists;
	}

	@Override
	public void addCategory(Category category) {
		QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
		String sql = "insert into category values (?,?)";
		Object [] params = {category.getCid(),category.getCname()};
		try {
			 queryRunner.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	@Override
	public Category findByCategoryCid(String cid) {
		  QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
	       String sql="SELECT * FROM category WHERE cid = ?";
	       Category category;
	       try {
	    	   category = queryRunner.query(sql, new BeanHandler<>(Category.class), cid);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return category;
	}

	@Override
	public void updateCategory(Category category) {
		  QueryRunner queryRunner=new QueryRunner(JdbcUtils.getDataSource());
		  String sql="UPDATE category SET cname = ? WHERE cid = ?";
		  try {
			queryRunner.update(sql, category.getCname(),category.getCid());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	@Override
	public void deleteByCategoryCid(Connection connection,Category category) {
		  QueryRunner queryRunner=new QueryRunner();
		  String sql="UPDATE book SET cid = null WHERE cid = ?";
		 try {
			 queryRunner.update( connection, sql,category.getCid());
			 sql ="DELETE FROM category WHERE cid = ?";
			 queryRunner.update( connection, sql,category.getCid());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
}
